

#include "NewFileDialog.h"
#include "GamePluginManager.h"
#include "EditorPlugin.h"


NewFileDialog::NewFileDialog(const QString &projPath, QWidget *parent /* = 0 */, Qt::WindowFlags flags /* = Qt::Tool */)
	: QDialog(parent, flags)
    , mProjPath(projPath)
{
	setupUi(this);

	if (projPath.isEmpty())
	{
		mProjectOpened = false;
	}
	else
	{
		mProjectOpened = true;
	}

	initListItems();
}

NewFileDialog::~NewFileDialog()
{

}

void NewFileDialog::initListItems()
{
	// Project
	QListWidgetItem *item = new QListWidgetItem(mListCtrlFiles, FT_PROJECT);
	item->setIcon(QIcon(":/Icons/Project.png"));
	item->setText(tr("Project"));
	item->setTextAlignment(Qt::AlignHCenter);
	item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);

	// Iterate all plugin.
	QLoaderList plugins = GamePluginManager::instance().plugins();
	QLoaderList::iterator itr = plugins.begin();
	while (itr != plugins.end())
	{
		EditorPlugin *plugin = qobject_cast<EditorPlugin*>((*itr)->instance());

		if (plugin != 0)
		{
			QString name = plugin->name();
            QIcon *icon = plugin->icon();

			item = new QListWidgetItem(mListCtrlFiles, plugin->pluginID());
			item->setIcon(*icon);
			item->setText(name);
			item->setTextAlignment(Qt::AlignHCenter);
			if (mProjectOpened)
			{
				item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
			}
			else
			{
				item->setFlags(Qt::NoItemFlags);
			}
		}		

		++itr;
	}
}

void NewFileDialog::onBtnBrowse()
{
	QString appDir = QApplication::applicationDirPath();

	QSettings settings;
	QString defaultDir = settings.value(DEFAULT_DIR, appDir).toString();

	QString dir = QFileDialog::getExistingDirectory(this, tr("Choose directory"), defaultDir);

	if (!dir.isEmpty())
	{
		// change the default directory and store it
		settings.setValue(DEFAULT_DIR, dir);
		QString path = QDir::fromNativeSeparators(dir) + "/";
		mEdtPath->setText(path);
	}
}

void NewFileDialog::onListCurrentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
	mFileType = (FileType)current->type();

	if (FT_PROJECT == mFileType)
	{
		mEdtPath->setEnabled(true);
		mBtnBrowse->setEnabled(true);
		mEdtPath->setText("");
	}
	else
	{
        EditorPlugin *plugin = GamePluginManager::instance().pluginInstance(mFileType);
		mEdtPath->setEnabled(false);
		mBtnBrowse->setEnabled(false);
        QString folder = plugin->fileFolder();
		QString path = mProjPath + folder + "/";
		mEdtPath->setText(path);
	}
}

void NewFileDialog::accept()
{
	mFileName = mEdtName->text();
	mFilePath = mEdtPath->text();

	if (mFileName.isEmpty() || mFilePath.isEmpty())
	{
		QMessageBox::warning(this, tr("GameEditor"), tr("File name or file path is empty !"));
	}
	else
	{
		QDialog::accept();
	}
}
